<?php
class blogs_model extends CI_Model{
	function __construct(){
		parent::__construct();
		$this->_table = 'blogs_article';
                $this->select = $select = "t1.*,t1.date_end,"
                        ."t2.title as cat_title,t2.slug as cat_slug,t2.id as cat_id,"
                        /*. "brand.name as 'brand_name',"
                        . "brand.image as 'brand_image',"
                        . "brand.slug as 'brand_slug',"
                        . "brand.count_like as 'brand_count_like',"
                        . "brand.count_comment as 'brand_count_comment',"
                        . "brand.total_score as 'brand_total_score',"
                        . "shop.name as 'shop_name',"
                        . "shop.image as 'shop_image',"
                        . "shop.slug as 'shop_slug',"
                        . "shop.count_like as 'shop_count_like',"
                        . "shop.count_comment as 'shop_count_comment',"
                        . "shop.total_score as 'shop_total_score'"*/;
		
	}
	
	public function get_all($params = array()){
		if ( ! empty($params['limit']))
		{
			$this->db->order_by('created','desc');
			$this->db->limit($params['limit']);
		}
		if ( ! empty($params['active']))
		{
			$this->db->where('active',1);
		}
		return $this->db->get($this->_table);
	}
	
	public function get( $id ){
		return $this->db->where("id",$id)->get($this->_table)->row_array();
	}
	public function get_many_by($params = array(),$page_size = 20,$data_search="",$page=0){	
		$where = "";
        if ( ! empty($params['cat_id'])){
			$this->db->where('cat_id',$params['cat_id']);
		}	
		if ( ! empty($params['cat_id']))
		{
			$this->db->where('cat_id',$params['cat_id']);
		}
		// get news  date_end
		if ( ! empty($params['date_end'])){
			if ($params['current_time'])
				$this->db->where('date_end >=',$params['date_end']);
			else 
				$this->db->where('date_end <',$params['date_end']);
		}

        if ( ! empty($params['where']))
		{
			$this->db->where($params['where']);
		}
		/*phan search*/
		/*
		$this->load->helper("handle_string");
		if(!empty($data_search)){
			$where = "";
			if(!empty($data_search["keyword"])){
				$data_search["keyword"] = str_replace(' ','-',$data_search["keyword"]);
				$data_search["keyword"] = utf8_to_ascii(preg_replace('/[^a-z0-9-]+/i','',$data_search["keyword"]));
				$where .= " AND t1.slug LIKE  '%".$data_search["keyword"]."%' ";
			}
			if(!empty($data_search["city_name"]))
				$where .= " AND t1.city_id = ".$data_search["city_name"]." ";
			if(!empty($data_search["district"]))
				$where .= " AND t1.district_id = ".$data_search["district"]." ";
			if(!empty($data_search["location_id"]) || !empty($data_search["trade_center_id"])){
				$where .= "AND (  ";
				if(!empty($data_search["location_id"])){
					$where .= " (1!=1 ";
						foreach($data_search["location_id"] as $key =>$value)
							$where .= " OR t1.location_id = $value ";
					$where .= " )";
				}
				if(!empty($data_search["trade_center_id"])){
					$where .= " OR (1!=1 ";
						foreach($data_search["trade_center_id"] as $key =>$value)
							$where .= " OR t1.trade_center_id = $value ";
					$where .= " )";
				}
				$where .= " ) ";
			}
			
			if(!empty($data_search["time_start"])||!empty($data_search["time_end"])){
				$time_start = !empty($data_search["time_start"])?strtotime($data_search["time_start"]):0;
				$time_end 	= !empty($data_search["time_end"])?strtotime($data_search["time_end"]):0;
				if(!empty($time_start) && !empty($time_end)){
					$where .= " AND ( 1=1 ";
					if($time_end < $time_start)
						$where .= " AND t1.date_start >= $time_end AND t1.date_end <= $time_start ";
					else
						$where .= " AND t1.date_start >= $time_start AND t1.date_end <=$time_end ";	
					$where .= " ) ";
			
				} 
				elseif(!empty($time_start) || !empty($time_end)){
					$time = (!empty($time_start))?$time_start:$time_end;
					$where .= " AND t1.date_start >= $time ";	 
				}
			}
		}
		*/
		/* end search */
		
		$this->db->select( $this->select);
		$this->db->join('blogs_categories t2','t2.id = cat_id AND t2.status = "1"',"LEFT");
		$this->db->get($this->_table." t1");
		$query  =  $this->db->last_query().$where;
		$total_row = $this->db->query($query)->num_rows();
		$query .= " ORDER BY created DESC "; 
		$this->db->limit($page_size);
		$this->db->offset($page);
		$articles = $this->db->query($query)->result();
		
		$model = new stdClass();
		$model->articles = $articles;
		$model->total_row = $total_row;
		return $model;
	}
	function get_blogs_page_home($limit){
		$query = $this->db
    		->select('blogs_article.id, blogs_article.title, blogs_article.slug, blogs_article.created, blogs_article.description,blogs_article.image,blogs_article.date_start,blogs_article.date_end,ser_users.id as user_id, ser_users.display_name')
			->from('blogs_article')
			->where('blogs_article.active','1')
			->where('ser_users.active','1')
			->order_by('blogs_article.created','desc')
			->limit($limit)
			->join('ser_users', 'blogs_article.create_by = ser_users.id', 'left outer')
			->get(); // See in the manual how to deal with query results. 
		return $query->result();
	}
	
	public function insert($data){
		$data['created'] = strtotime(date('Y-m-d H:i'));
        //if ($data['date_start'] !='')  $data['date_start'] = strtotime($data['date_start']);
        //if ($data['date_end'] !='' ) $data['date_end'] = strtotime($data['date_end']);
		$data['image'] = isset($data['image']) ? $data['image'] : "";
		$this->db->insert("blogs_article",$data);
		return $this->db->insert_id();
	}
	public function update($id,$data){
                if (!empty($data['date_start'])) {
					$data['date_start'] = strtotime($data['date_start']);
				}
                if (!empty($data['date_end'])) $data['date_end'] = strtotime($data['date_end']);
				$this->db->where("id",$id)->update("blogs_article",$data);
                //parent::update($id,$data);
	}
	function get_total_row(){
		$result = 0;
		$q = $this->db->last_query();
		$result = count($this->db->query($q)->result());
//		echo $this->db->last_query();
		return $result;
	}
	
	function delete( $id ){
		$this->db->where("id",$id)->delete($this->_table);
	}
	
	//news/categories return categories , articles
	function categories( $slug , $page_size = 5, $page_index = 0 ){
		$model = new stdClass();
		$this->_table = 'blogs_categories';		
		$this->db->where('slug',$slug);
		$cat_data = $this->db->get($this->_table)->row();
		//print_r($cats);exit;
		//articles
		
		$this->_table = 'blogs_article';
		$this->db->where('cat_id',$cat_data->id);
		$total_row = $this->db->count_all_results($this->_table);//$this->get_total_row();
		//total row
		$this->_table = 'blogs_article';
		$this->db->where('cat_id',$cat_data->id);
		$this->db->limit($page_size, $page_index * $page_size);
		
		$articles = $this->db->get($this->_table)->result();
		
		$model->categories = $cat_data;
		$model->articles = $articles;
		$model->total_row = $total_row;
		return $model;
	}
	
	function detail( $slug){
		$this->db->where('slug', $slug);
		$this->db->where('active', 1);
		$result = $this->db->get($this->_table)->row();
		if(empty($result)) redirect('404');
        
		$this->db->set('count_view', '`count_view`+ 1', FALSE);
		$this->db->where('slug',$slug);
		$this->db->update("blogs_article");
		
        return $result;
	}
	public function related_blogs($id_blog,$id_cat){
		return $this->db->where("id <>",$id_blog)->where("cat_id",$id_cat)->where("active",1)->limit(6)->get("blogs_article")->result();
	}
	public function get_blogs_product($product_id){
		return $this->db->where("id IN(".trim($product_id,",").")")->get("products")->result();
	}
}